import { Component, OnInit, Input, Output, EventEmitter, ElementRef } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { config } from '../smartadmin.config';
import { Router } from "@angular/router";

declare var $: any;
declare var BMap: any;
declare var toWGS84: any;
declare var BMAP_ANCHOR_BOTTOM_LEFT:any;
declare var BMAP_STATUS_SUCCESS: any;
declare var INFOBOX_AT_TOP: any;
declare var BMAP_ANCHOR_BOTTOM_RIGHT: any;
declare var BMAP_NORMAL_MAP: any;
declare var BMAP_HYBRID_MAP: any;
declare var BMAP_ANCHOR_TOP_RIGHT: any;
declare var BMAP_ANCHOR_TOP_LEFT: any;
@Component({
	selector: 'sa-bmap-tools',
	templateUrl: './bmapTools.component.html',
})
export class BmapToolsComponent implements OnInit {
	@Input() baiduMap: any = null;
	@Input() baiduMapId: any = 'baiduMap'; //标识Id
	@Input() showPanorama: boolean = true;
	@Input() isShowCity: boolean = true; // 是否打开工具栏下拉框
	@Input() isOpen: boolean = false; // 是否打开工具栏下拉框
	@Input() isShowControl: boolean = false ; // 是否显示地图控件菜单列表
	@Input() isShowMapType: boolean = false; // 是否显示地图类型
	@Input() isShowOverView: boolean = false; // 是否显示缩略图
	@Input() isShowScale: boolean = false; // 是否显示比例尺
	@Input() isPanorama: boolean = false; // 是否是全景
	@Input() isBigMap: boolean = false; // 拉框放大
	@Input() bigDrag: any; // 放大的
	@Input() isShrinkMap: boolean = false; // 拉框缩小
	@Input() shrikeDrag: any; // 缩小的
	@Input() isMetterMap: boolean = false; // 测量间距 
	@Input() isShowPosition: boolean = false; // 位置采集
	@Input() geoc: any = ''; // 地图位置采集的
	@Input() infoBox: any = "";
	@Input() marker: any = "";
	@Input() myMap: any;
	@Input() isShowZoom: boolean = false; //是否显示缩放控件
	@Input() reduceHeight: any = '16'; //是否显示缩放控件
	@Input() reduceWidth: any = '461'; //是否显示缩放控件
	@Input() reduceRight: any = '380';
	@Input() baiduMapHeight: any = '10px';
	@Output() sensorSelected = new EventEmitter();

	overViewOpen: any;
	top_left_control: any;
	tilelayer: any;
	stCtrl: any;
	// mapType1: any;
	citySize: any;// 城市选择的控件
	mapSize: any = 10
	constructor(private jsonApiService: JsonApiService, private el: ElementRef, private router: Router) {}

	ngOnInit() {
		var that = this;
		
		// 地图类型
		// that.mapType1 = new BMap.MapTypeControl(
		// 	{
		// 		// type:BMAP_MAPTYPE_CONTROL_MAP,
		// 		mapTypes: [BMAP_NORMAL_MAP,BMAP_HYBRID_MAP],
		// 		anchor: BMAP_ANCHOR_BOTTOM_RIGHT,
		// 		offset: new BMap.Size(85, 40)
		// 	}
		// );

		
	}
	ngOnChanges() {
		var that = this;
		if(that.baiduMap != 'undefined' && that.baiduMap != 'null' && that.baiduMap){

			that.citySize = new BMap.Size(this.reduceWidth, this.reduceHeight);
			// that.tilelayer = new BMap.PanoramaCoverageLayer() // 全景地图的覆盖层
			// that.stCtrl = new BMap.PanoramaControl(); //构造全景控件
			// that.stCtrl.setOffset(new BMap.Size(110, 100));
			// that.stCtrl.setAnchor(BMAP_ANCHOR_BOTTOM_RIGHT);
			if(that.isShowCity){
				var timerDate = setTimeout(() => {
					var cityList = new BMap.CityListControl({
						anchor: BMAP_ANCHOR_TOP_RIGHT,
						offset: that.citySize
						// 切换城市之前事件
						// onChangeBefore: function(){
						//    alert('before');
						// },
						// 切换城市之后事件
						// onChangeAfter:function(){
						//   alert('after');
						// }
					});
					that.baiduMap.addControl(cityList);
					let timer1 = setTimeout(() => {
						$(".ui_city_change_top").click(that.cityClick)
						clearTimeout(timer1)
						timer1 = null;
					}, 800);
					clearTimeout(timerDate)
					timerDate = null
					that.mapType(); //默认就是显示缩略图
				}, 500);
			}else{
				that.mapType(); //默认就是显示缩略图
			}
			
			if(that.isShowZoom){
				this.baiduMap.centerAndZoom(new BMap.Point(117.7953288, 28.2862345), 5); //初始化地图，设置中心点坐标和地图级别
				this.baiduMap.addControl(new BMap.NavigationControl({anchor:BMAP_ANCHOR_BOTTOM_RIGHT,offset: new BMap.Size(12, 24)}));//缩放控件
				this.baiduMap.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
				this.baiduMap.addEventListener("zoomend", function() {
					that.mapSize = this.getZoom();
				});
			}

			that.overViewOpen = new BMap.OverviewMapControl({offset:{width:10,height:70},anchor:BMAP_ANCHOR_TOP_LEFT,isOpen:true})
			that.top_left_control = new BMap.ScaleControl({offset:{width:12,height:50},anchor: BMAP_ANCHOR_TOP_LEFT});// 左上角，添加比例尺
			
		}

		
	}
	ngOnDestroy() {
	}
	// 打开城市列表 关闭工具箱
	cityClick(){
		var that = this;
		$(".toolText").css('color',"#393939");
		$(".toolListTab").css("display","none")
		that.isOpen = false;
		$(".showContrl").removeClass("activeLi")
		$(".controlList").css("display","none");
		that.isShowControl = false;
	}
	// 工具箱初始化  打开工具箱才初始化
	mapInit(map){
		var that = this;
		that.myMap = map;
		// 放大的方法
		that.bigDrag = new BMapLib.RectangleZoom(that.myMap, {
			followText: "拖拽鼠标进行操作"
		});
		// 缩小的方法
		that.shrikeDrag = new BMapLib.RectangleZoom(that.myMap, {
			zoomType:1,
			followText: "拖拽鼠标进行操作"
		});
		// 鼠标测距
		// myDis = new BMapLib.DistanceTool(myMap,{lineColor : "#ff6319",lineStyle: "solid"});
		// myDis.addEventListener("drawend", function(e) { 
		//     removeLiClass("metterMap")
		//     myDis.close();
		//     isMetterMap = false
		// });
		// 位置采集
		that.geoc = new BMap.Geocoder();
	}
	// 打开工具箱
	openTool(){
		var that = this;
		if(!that.isOpen){
			that.mapInit(that.baiduMap)
			//     color: #393939;
			$(".toolText").css('color',"#579AFC");
			$(".toolListTab").css("display","block")
			 // 关闭城市列表
			 $("#popup_close").click();
			 that.isOpen = true
		}else{
			that.clearAll();
			$(".toolText").css('color',"#393939");
			$(".toolListTab").css("display","none")
			that.isOpen = false;
		}
	}
	// 点击了控件菜单
	clickControl(){
		var that = this;
		// 打开
		if(!that.isShowControl){
			that.clearAll()
			$(".showContrl").addClass("activeLi")
			$(".controlList").css("display","block");
			that.isShowControl = true;
		}else{
			$(".showContrl").removeClass("activeLi")
			$(".controlList").css("display","none");
			that.isShowControl = false;
		}
	}
	mapType(){
		// 地图类型
		var mapType1 = new BMap.MapTypeControl(
			{
				// type:BMAP_MAPTYPE_CONTROL_MAP,
				mapTypes: [BMAP_NORMAL_MAP,BMAP_HYBRID_MAP],
				anchor: BMAP_ANCHOR_BOTTOM_RIGHT,
				offset: new BMap.Size(85, 40)
			}
		);
		var that = this;
		// 如果没打开就打开
		if(!that.isShowMapType){
			$(".mapType").addClass("activeLi")
			$(".isShowMapType").addClass("is-checked")
			that.baiduMap.addControl(mapType1);
			$("div[title='显示普通地图']").css("display","none") 
			$("div[title='显示带有街道的卫星影像']").css("display","none") 
			that.isShowMapType = true;
		}else{
			$(".mapType").removeClass("activeLi")
			$(".isShowMapType").removeClass("is-checked")
			that.baiduMap.removeControl(mapType1);
			that.isShowMapType = false;
		}
	}
	overViewControl(){
		var that = this;
		// 如果没有缩略图就打开缩略图
		if(!that.isShowOverView){
			$(".overViewMap").addClass("activeLi")
			$(".isShowOverView").addClass("is-checked")
			that.baiduMap.addControl(that.overViewOpen);      //左下角，打开
			that.isShowOverView = true
		}else{
			$(".overViewMap").removeClass("activeLi")
			$(".isShowOverView").removeClass("is-checked")
			that.baiduMap.removeControl(that.overViewOpen);
			that.isShowOverView = false
		}
	}
	scaleControl(){
		var that = this;
		if(!that.isShowScale){
			$(".scaleRuler").addClass("activeLi")
			$(".isShowScale").addClass("is-checked")
			that.baiduMap.addControl(that.top_left_control);      //左下角，打开
			that.isShowScale = true
		}else{
			$(".scaleRuler").removeClass("activeLi")
			$(".isShowScale").removeClass("is-checked")
			that.baiduMap.removeControl(that.top_left_control);
			that.isShowScale = false
		}
	}
	// 拉框放大
	bigMapControl(){
		var that = this;
		if(!that.isBigMap){
			that.clearAll()
			$(".bigMap").addClass("activeLi")
			that.shrikeDrag.close();  
			that.bigDrag.open();  //开
			that.isBigMap=true;
		}else{
			$(".bigMap").removeClass("activeLi")
			that.bigDrag.close(); 
			that.isBigMap=false;
		}
	} 
	// 拉框缩小
	shrinkMapControl(){
		var that = this;
		// 拉框缩小
		if(!that.isShrinkMap){
			that.clearAll()
			$(".shrinkMap").addClass("activeLi")
			that.shrikeDrag.open();  //开
			that.isShrinkMap=true;
		}else{
			$(".shrinkMap").removeClass("activeLi")
			that.shrikeDrag.close();  
			that.isShrinkMap=false;
		}
	}
	ddPoint_lng: any = '';
	ddPoint_lat: any = '';
	// 开启位置采集
	showPositionControl(){
		var that = this;
		that.myMap.removeEventListener("click",markePoint);
		if(!that.isShowPosition){
			that.clearAll();
			var infoBoxLen = $('#' + that.baiduMapId + ' .positionInfoBox');
			for(let i=0;i< infoBoxLen.length;i++){
				infoBoxLen[i].remove()
			}
			$(".showPosition").addClass("activeLi")
			//单击获取点击的经纬度
			that.myMap.addEventListener("click",markePoint,false);
			that.isShowPosition = true
			
		}else{
			$(".showPosition").removeClass("activeLi")
			that.myMap.removeOverlay(that.marker);
			that.myMap.removeEventListener("click",markePoint,false);
			that.infoBox.close();
			that.isShowPosition = false
		}


		// 地图打点的函数
		function markePoint(e){
			// that.myMap = that.baiduMap;
			// 取消窗口
			that.myMap.removeOverlay(that.marker)
			
			if(that.infoBox){
				that.infoBox.close();
				that.infoBox = ''
			}
			var infoBoxLen = $('#' + that.baiduMapId + ' .positionInfoBox');
			for(let i=0;i< infoBoxLen.length;i++){
				infoBoxLen[i].remove()
			}
			if(!that.isShowPosition){
				return;
			}
			// let baiduPoint = JSON.parse(JSON.stringify(e.point));
			// let ddPoint = toWGS84(baiduPoint)
			// 如果不在中国境内就用它原本的  如果在 就用接口
			if(!e.point){
				that.baiduPosition(e.point);
			}else{
				var point = new BMap.Point(e.point.lng,e.point.lat);
				that.marker = new BMap.Marker(point);  // 创建标注
				that.myMap.addOverlay(that.marker);              // 将标注添加到地图中
				var opts = {
					offset :  new BMap.Size(0, 8),
					boxStyle:{
						opacity: "0.8",
						background: "#fff",
						width: "305px",
						height: "auto"
					},
					boxClass : "positionInfoBox",
					closeIconUrl:"assets/img/closeHei.png",
					closeIconMargin: "7px 8px 0 0",
					enableAutoPan: true,
					align: INFOBOX_AT_TOP
				}
				let reqdata = {
					'lng': e.point.lng,
					'lat': e.point.lat,
					'type': 2
				}
				if(e.point.lng == that.ddPoint_lng && e.point.lat == that.ddPoint_lat){
					return
				}
				that.jsonApiService.http_obj('system/getAddressByLocation.html',reqdata).subscribe(data=> {
					if(data.success){
						if(data.message=="坐标转换异常！"){
							that.baiduPosition(e.point)
						}else{
							var positionHtml = '<div class="infoWrap"><h2>位置信息</h2><ul> <li>经度：'+e.point.lng+'</li> <li>纬度：'+e.point.lat+'</li><li class="positionInfo"><span>位置：</span><span>'+data.message+'</span></li></ul></div><div class="delta"></div>'
							that.infoBox = new BMapLib.InfoBox(that.myMap,positionHtml, opts);  // 创建信息窗口对象 
							that.infoBox.open(that.marker);
						}
					}
				})
			}

			that.ddPoint_lng = e.point.lng;
			that.ddPoint_lat = e.point.lat;
		}
	   
	}
	baiduPosition(baiduPoint){
		var position = "";
		var that = this;
		// 根据经纬度解析
		this.geoc.getLocation(baiduPoint, function(rs){
			var addComp = rs.addressComponents;
			if(addComp.province!=addComp.city){
				position += addComp.province
			}
			position+=(addComp.city+addComp.district+addComp.street+addComp.streetNumber)
			var opts = {
				offset :  new BMap.Size(0, 8),
				boxStyle:{
					opacity: "0.8",
					background: "#fff",
					width: "250px",
					height: "auto"
				  },
				  boxClass : "positionInfoBox",
				  closeIconUrl:"assets/img/closeHei.png",
				  closeIconMargin: "7px 8px 0 0",
				  enableAutoPan: true,
				  align: INFOBOX_AT_TOP
			}
			var positionHtml = '<div class="infoWrap"><h2>位置信息</h2><ul> <li>经度：'+baiduPoint.lng+'</li> <li>纬度：'+baiduPoint.lat+'</li><li class="positionInfo"><span>位置：</span><span>'+position+'</span></li></ul></div><div class="delta"></div>'
			that.infoBox = new BMapLib.InfoBox(that.myMap,positionHtml, opts);  // 创建信息窗口对象 
			that.infoBox.open(that.marker);
		}); 
	}
	// 点击自然地图
	normalMapClick(){
		var that = this;
		$("#mapTypeWrap li").removeClass("active")
		$(".normal").addClass("active")
		// 关闭全景
		$(".pano_close").click()
		// that.baiduMap.removeTileLayer(that.tilelayer)
		// that.stCtrl.hide();
		that.isPanorama = false
	
		$("div[title='显示普通地图']").click();
	}
	// 打开卫星地图
	satelliteMapClick(){
		var that = this;
		$("#mapTypeWrap li").removeClass("active")
		$(".nosatellitermal").addClass("active")
		
		// 关闭全景
		$(".pano_close").click()
		// that.baiduMap.removeTileLayer(that.tilelayer)
		// that.stCtrl.hide();
		that.isPanorama = false
		$("div[title='显示带有街道的卫星影像']").click();
	}
	// 打开全景的函数
	panoramaCoverControl(){
		var that = this;
		$("#mapTypeWrap li").removeClass("active")
		$(".panorama").addClass("active")
		
		$(".pano_close").css('top',this.baiduMapHeight)
		// if(!isPanorama){
			// 覆盖区域图层测试
			that.baiduMap.addTileLayer(that.tilelayer);
			that.baiduMap.addControl(that.stCtrl);//添加全景控件
			that.stCtrl.show();
			that.isPanorama = true 
			var geolocation = new BMap.Geolocation();
			geolocation.getCurrentPosition(function(r){
				if(this.getStatus() == BMAP_STATUS_SUCCESS){
					that.baiduMap.panTo(r.point);
					that.baiduMap.centerAndZoom(new BMap.Point(r.point.lng, r.point.lat), 12);
				
				}
			},{enableHighAccuracy: true})
		// }else{
		//     baiduMap.removeTileLayer(tilelayer)
		//     stCtrl.hide();
		//     isPanorama = false
		// }
	}
	//  清除所有的工具的标注
	clearAll(){
		var that = this;
		$(".tool").removeClass("activeLi");
		that.bigDrag.close(); 
		that.isBigMap=false;
		that.shrikeDrag.close();  
		that.isShrinkMap=false;
		// myDis.close();
		that.isMetterMap = false;
		// 清除所有的测量数据
		$(".BMap_Marker[title='清除本次测距']").click()
		// 关闭位置信息
		that.myMap.removeOverlay(that.marker)
		if(that.infoBox){
			that.infoBox.close();
		}
		// myMap.clearOverlays();
		that.isShowPosition = false
		// 关闭工具框
		that.isShowControl = false;
		$(".controlList").css("display","none")
	}
	mapHeight: any;
	mapWidth: any;
	openFull() {
		let deviceHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
		if (!$("body").hasClass("full-map")) {
			this.mapHeight = $("#" + this.baiduMapId).css('height');
			this.mapWidth = $("#" + this.baiduMapId).css('width');
			$("body").addClass("full-map");
			$(this).find(".fa").removeClass("fa-arrows-alt").addClass("fa-compress");
			$("#" + this.baiduMapId).css("height", $(window).height());
			$("#" + this.baiduMapId).css("width", $(window).width());
			$(window).resize(function () {
				$("#" + this.baiduMapId).css("height", $(window).height());
				$("#" + this.baiduMapId).css("width", $(window).width());
			});
		} else {
			$("body").removeClass("full-map");
			$(this).find(".fa").removeClass("fa-compress").addClass("fa-arrows-alt");
			// $("#baiduMap").height(this.mapHeight);
			// $("#baiduMap").width(this.mapWidth);
			$("#" + this.baiduMapId).css("height",parseInt(this.mapHeight.substring(0,this.mapHeight.length-2)));
			$("#" + this.baiduMapId).css("width", parseInt(this.mapWidth.substring(0,this.mapWidth.length-2)));
		}
	}
}